<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>

  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  <script src="https://unpkg.com/vuex@2.0.0/dist/vuex.js"></script>
</head>

<body>

  <div id="app">

    <count-button type="increment"></count-button>
    {{$store.state.num}}
    <count-button type="decrement"></count-button>

    <hr>
    {{$store.getters.getNum}}
  </div>

  <script>

    Vue.component('count-button', {
      props: ['type'],
      template: `
    <button @click="handleClick">{{getBtnText}} </button>
  `,
      computed: {
        getBtnText() {
          if (this.type === 'increment') {
            return '+'
          } else {
            return '-'
          }
        }
      },
      methods: {
        handleClick() {
          if (this.type === 'increment') {
            //正确的写法，同步的数据更新
            this.$store.commit('incrementCount')
            //正确的写法，异步的数据更新
            // this.$store.dispatch('asyncIncrementCount')
            //可以修改成功，错误的写法
            // this.$store.state.num=555;
          } else {
            this.$store.commit('decrementCount',2)
          }
        }
      }
    })


    var store = new Vuex.Store({
      state: {
        num: 100
      },
      mutations: {
        incrementCount(state) {
          state.num += 1;
          //异步操作不建议卸载这
          // setTimeout(()=>{
          //   // context.commit('incrementCount')
          //   state.num += 1;
          // },2000)
        },
        decrementCount(state,num) {
          state.num -= num;
        }
      },
      actions:{
        asyncIncrementCount(context){
          setTimeout(()=>{
            context.commit('incrementCount')
          },2000)
        }
      },
      getters:{
        getNum(state){
          return state.num *2;
        }
      }
    })

    var vm = new Vue({
      el: "#app",
      store
    })
  </script>

</body>

</html>